﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Kira.Compiler.Bods
{
    [XmlElementMapping("DITransformCall", "name", "Case_Operation")]
    public class DICaseOperation : BodsTransform
    {
        public IEnumerable<DISwitch> Switchs
        {
            get
            {
                return this.GetElement("DICase").GetElements<DISwitch>();
            }
        }

        public String InputName
        {
            get { return this.GetElement("DIInputView").GetAttrbuteValue("name"); }
        }

        public override IEnumerable<string> InputNames
        {
            get { return new string[] { this.InputName }; }
        }

        public override IEnumerable<string> OutputNames
        {
            get { return from c in this.Switchs select c.OutputName; }
        }

        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(GetComments("Case_Operation"));
            foreach (var i in this.Switchs)
            {
                sb.Append("WITH ").Append(i.OutputName).Append(" AS (SELECT * FROM ").Append(this.InputName).Append(" WHERE ").Append(i.IsDefault ? "1 = 1 " : i.Expression.ToString()).AppendLine(");");
            }
            return sb.ToString();
        }

    }

    [XmlElementMapping("DISwitch")]
    public class DISwitch : BodsElementBase
    {

        public String Label
        {
            get { return this.GetAttrbuteValue("label"); }
        }
        public String OutputName
        {
            get
            {
                return this.GetAttrbuteValue("outputView");
            }
        }

        public bool IsDefault
        {
            get
            {
                return bool.Parse(this.GetAttrbuteValue("isDefault"));
            }
        }

        public BodsExpression Expression
        {
            get
            {
                return this.GetElement("DIExpression").FirstElement as BodsExpression;
            }
        }
    }
}
